<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/08/18
 * Time: 17:57
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\library\Tools;
use app\common\model\CsBlacklist;
use app\common\model\Orders;
use think\console\input\Option;

/**
 * 检查订单
 * Class OrderCheck
 * @package app\command
 */
class OrderCheck extends BaseCommand
{
    protected function configure()
    {
        $this->setName('order_check')
            ->addOption("ids", null, Option::VALUE_REQUIRED, "订单id，多个使用英文逗号分开")
            ->addOption("start_date", null, Option::VALUE_REQUIRED, "开始时间，默认为今天")
            ->addOption("end_date", null, Option::VALUE_REQUIRED, "结束导入时间")
            ->setDescription("检查订单是否为正常订单");
    }

    protected function handler()
    {
        $where = [
            ["order_status", "IN", [Orders::ORDER_WAIT, Orders::ORDER_WAREHOUSE, Orders::ORDER_LOCK]]
        ];
        if($this->input->hasOption("ids") && ($ids = replaceStr($this->input->getOption("ids"))))
        {
            $where[] = ["order_id", "in", $ids];
        }
        else
        {
            // 处理时间范围
            $startDate = $this->input->hasOption('start_date')
                ? $this->input->getOption('start_date')
                : Tools::addDate(0);
            $endDate = $this->input->hasOption('end_date')
                ? $this->input->getOption('end_date')
                : Tools::addDate(1);
            $where = array_merge($where, [
                        ['create_time', 'egt', $startDate],
                        ['create_time', 'elt', $endDate]
                    ]);
        }

        // 是否为风险订单
        Orders::where($where)->chunk($this->defChunk, function($orders)
        {
            foreach($orders as $order)
            {
                // 检查是否为风险订单
                if(CsBlacklist::inBlackBox($order))
                {
                    $order->order_status = Orders::ORDER_RISK;
                }
                // 检查是否为异常订单
                else if($this->checkOrder($order))
                {
                    $order->order_status = Orders::ORDER_EXCEPTION;
                }
                $order->save();
            }
        });
    }

    /**
     * 检查订单的完整性，是否为异常订单
     * @param Orders $order 订单
     * @return bool
     */
    private function checkOrder(Orders $order)
    {
        // @todo 检查订单的完整性，如果订单不完整，则标记为异常订单
        return false;
    }
}